﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DNA.Models;
using System.Xml;
using System.IO;

namespace DNA.Controllers
{ 
    public class ResearchController : Controller
    {
        private DNAAnalysisEntities db = new DNAAnalysisEntities();

        //
        // GET: /Research/

        public ViewResult Index()
        {
            var research = db.Research.Include("User");
            return View(research.ToList());
        }

        //
        // GET: /Research/Details/5

        public ViewResult Details(int id)
        {
            Research research = db.Research.Single(r => r.Id == id);
            return View(research);
        }

        //
        // GET: /Research/Create

        public ActionResult Create()
        {
            ViewBag.User_Id = new SelectList(db.User, "Id", "Name");
            return View();
        } 

        //
        // POST: /Research/Create

        [HttpPost]
        public ActionResult Create(Research research)
        {
            if(ModelState.IsValid)
            {
                db.Research.AddObject(research);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.User_Id = new SelectList(db.User, "Id", "Name", research.User_Id);
            return View(research);
        }

        //
        // GET: /Research/Importar

        public ActionResult Importar()
        {
            ViewBag.User_Id = new SelectList(db.User, "Id", "Name");
            return View();
        } 

        [HttpPost]
        public ActionResult Importar(Research research)
        {

            //Caminho do arquivo xml
            string arquivo = "";

            //Prepara a leitura do arquivo
            foreach (string fileName in Request.Files)
            {
                HttpPostedFileBase postedFile = Request.Files[fileName];

                postedFile.SaveAs(Server.MapPath("~/XMLs/") + Path.GetFileName(postedFile.FileName));

                arquivo = Server.MapPath("~/XMLs/") + Path.GetFileName(postedFile.FileName);
            }

            //Cria uma variavel do tipo xml
            XmlDocument xmlDoc = new XmlDocument();

            //Carrega o arquivo xml
            xmlDoc.Load(arquivo);


            //Percorre todos os nós do arquivo xml
            for (int i = 0; i < xmlDoc.DocumentElement.ChildNodes.Count; i++)
            {
                XmlNode root = xmlDoc.DocumentElement.ChildNodes[i];
                Research res = new Research();
                ResearchDiseaseProbability resprob = new ResearchDiseaseProbability();
                //Pega dados da pesquisa
                string email = root.SelectSingleNode("researcher").ChildNodes[0].Value;
                string doenca = root.SelectSingleNode("illness").ChildNodes[0].Value;
                string padrao = root.SelectSingleNode("pattern").ChildNodes[0].Value;
                double probabilidade = double.Parse(root.SelectSingleNode("probability").ChildNodes[0].Value);

                //Pega ID do usuario dono da pesquisa
                try
                {
                    User user = db.User.Single(u => u.Email == email);
                    res.User_Id = user.Id;
                }
                catch (Exception ex)
                {
                    ex.Message.ToString();
                    //Email n cadastrado
                }

                //Pega Id da doença da pesquisa
                try
                {
                    Disease disease = db.Disease.Single(u => u.Name == doenca);
                    resprob.Disease_Id = disease.Id;
                }
                catch (Exception ex)
                {
                    ex.Message.ToString();
                    //Email n cadastrado
                }

                //Insere o padrao no obj research
                res.DNAPartialPattern = padrao;

                //Insere a probabilidade no obj ReseachProb~
                resprob.Probability =probabilidade;

                res.ResearchDiseaseProbability.Add(resprob);
                
                db.Research.AddObject(res);
                db.SaveChanges();
            }

            return RedirectToAction("Index"); 
        }
        
        //
        // GET: /Research/Edit/5
 
        public ActionResult Edit(int id)
        {
            Research research = db.Research.Single(r => r.Id == id);
            ViewBag.User_Id = new SelectList(db.User, "Id", "Name", research.User_Id);
            return View(research);
        }

        //
        // POST: /Research/Edit/5

        [HttpPost]
        public ActionResult Edit(Research research)
        {
            if (ModelState.IsValid)
            {
                db.Research.Attach(research);
                db.ObjectStateManager.ChangeObjectState(research, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.User_Id = new SelectList(db.User, "Id", "Name", research.User_Id);
            return View(research);
        }

        //
        // GET: /Research/Delete/5
 
        public ActionResult Delete(int id)
        {
            Research research = db.Research.Single(r => r.Id == id);
            return View(research);
        }

        //
        // POST: /Research/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            Research research = db.Research.Single(r => r.Id == id);
            db.Research.DeleteObject(research);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}